package cn.com.headfree.sysmenu.controller;

import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.IscUser;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.sysmenu.entity.TSysMenu;
import cn.com.headfree.sysmenu.entity.TSysRole;
import cn.com.headfree.sysmenu.entity.TSysUserRole;
import cn.com.headfree.sysmenu.service.IRoleService;
import cn.com.headfree.sysmenu.vo.RoleQueryVo;
import cn.com.headfree.sysmenu.vo.SysRoleVo;
import cn.com.headfree.sysmenu.vo.TreeSelect;
import cn.com.headfree.sysmenu.vo.UserRoleQueryVo;
import com.gta.edu.sdk.common.dto.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//角色信息
@Api(value = "角色信息",tags = {"角色信息接口"})//描述controller
@RestController
@RequestMapping(value = "/role", produces = "application/json;charset=UTF-8")
public class SysRoleController extends ExBaseController {
    private static final Logger LOG = LogManager.getLogger(SysRoleController.class);

    @Autowired
    IRoleService roleService;

    @ApiOperation(value = "获取角色全部列表",notes = "获取角色全部列表",httpMethod = "POST")//描述接口
    @RequestMapping("/getRoleList")
    public ResultData getRoleList(@RequestBody SysRoleVo sysRole, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            User user = this.getLoginUserInfo(request);
            List<TSysRole> list = roleService.findRoleList(sysRole,user.getBaseOrgId());
            rs.setData(list);
            LOG.info("查询角色信息成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("查询角色信息失败！");
            e.printStackTrace();
        }
        return rs;
    }

    @ApiOperation(value = "获取角色分页列表",notes = "获取角色分页列表",httpMethod = "POST")//描述接口
    @RequestMapping("/getPageRole")
    public ResultData getPageRole(Page<TSysRole> page, @RequestBody SysRoleVo sysRole, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            User user = this.getLoginUserInfo(request);
            roleService.getPageRole(page,sysRole,user.getBaseOrgId());
            rs.setData(page);
            LOG.info("查询角色分页信息成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("查询角色分页信息失败！");
            e.printStackTrace();
        }
        return rs;
    }

    @ApiOperation(value = "新增角色",notes = "新增角色",httpMethod = "POST")//描述接口
    @RequestMapping("/addRole")
    public ResultData addRole(@RequestBody TSysRole sysRole, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            if(StringUtils.isBlank(sysRole.getRoleName())){
                rs.setErrorMsg("角色名称不能为空！");
                return rs;
            }
            if(StringUtils.isBlank(sysRole.getOrgId())){
                rs.setErrorMsg("单位id不能为空！");
                return rs;
            }
            List<TSysRole> list = roleService.findRoleListByRoleName(null,sysRole.getRoleName());
            if(list.size()>0){
                rs.setErrorMsg("角色名称已经存在！");
                return rs;
            }
            roleService.addRole(sysRole);
            rs.setSuccess(true);
            LOG.info("新增角色成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("新增角色失败！");
            e.printStackTrace();
        }
        return rs;
    }

    @ApiOperation(value = "更新角色",notes = "更新角色",httpMethod = "POST")//描述接口
    @RequestMapping("/updateRole")
    public ResultData updateRole(@RequestBody TSysRole sysRole, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            rs.setSuccess(false);
            if(StringUtils.isBlank(sysRole.getId())){
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            if(StringUtils.isBlank(sysRole.getRoleName())){
                rs.setErrorMsg("角色名称不能为空！");
                return rs;
            }
            if(StringUtils.isBlank(sysRole.getOrgId())){
                rs.setErrorMsg("单位id不能为空！");
                return rs;
            }
            List<TSysRole> list = roleService.findRoleListByRoleName(sysRole.getId(),sysRole.getRoleName());
            if(list.size()==0){ //角色名称已改
                List<TSysRole> list1 = roleService.findRoleListByRoleName(null,sysRole.getRoleName());
                if(list1.size()>0){
                    rs.setErrorMsg("角色名称已经存在！");
                    return rs;
                }
            }
            roleService.updateRole(sysRole);
            rs.setSuccess(true);
            LOG.info("更新角色成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("更新角色失败！");
            e.printStackTrace();
        }
        return rs;
    }

    @ApiOperation(value = "验证角色名称是否唯一",notes = "验证角色名称是否唯一",httpMethod = "POST")//描述接口
    @RequestMapping("/checkRoleName")
    public ResultData checkRoleName(@RequestBody TSysRole sysRole, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            rs.setSuccess(true);
            HashMap map = new HashMap();
            Boolean flag = false;
            if (StringUtils.isBlank(sysRole.getRoleName())) {
                map.put("flag",flag);
                rs.setData(map);
                rs.setErrorMsg("角色名称不能为空！");
                return rs;
            }
            if(StringUtils.isBlank(sysRole.getId())){ // 新增
                List<TSysRole> list = roleService.findRoleListByRoleName(null,sysRole.getRoleName());
                if(list.size()>0){
                    map.put("flag",flag);
                    rs.setData(map);
                    rs.setErrorMsg("角色名称已经存在！");
                    return rs;
                }
            }else{  // 修改
                List<TSysRole> list = roleService.findRoleListByRoleName(sysRole.getId(),sysRole.getRoleName());
                if(list.size()==0){ //角色名称已改
                    List<TSysRole> list1 = roleService.findRoleListByRoleName(null,sysRole.getRoleName());
                    if(list1.size()>0){
                        map.put("flag",flag);
                        rs.setData(map);
                        rs.setErrorMsg("角色名称已经存在！");
                        return rs;
                    }
                }
            }
            flag = true;
            map.put("flag",flag);
            rs.setData(map);
            LOG.info("验证角色名称是否唯一成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("验证角色名称是否唯一失败！");
            e.printStackTrace();
        }
        return rs;
    }

    @ApiOperation(value = "更新角色状态",notes = "更新角色状态",httpMethod = "POST")//描述接口
    @RequestMapping("/updateRoleStatus")
    public ResultData updateRoleStatus(@RequestBody TSysRole sysRole, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            rs.setSuccess(false);
            if(StringUtils.isBlank(sysRole.getId())){
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            if(StringUtils.isBlank(sysRole.getStatus())){
                rs.setErrorMsg("角色状态不能为空！");
                return rs;
            }
            roleService.updateRoleStatus(sysRole);
            rs.setSuccess(true);
            LOG.info("更新角色成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("更新角色失败！");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 传参：角色id数组（roleIds）
     */
    @ApiOperation(value = "删除角色",notes = "删除角色，传参：角色id数组（roleIds）",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "roleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/deleteRole")
    public ResultData deleteRole(@RequestBody RoleQueryVo roleQueryVo, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            String[] roleIds = roleQueryVo.getRoleIds();

            if(null!=roleIds&&roleIds.length>0){
                Boolean deleteFlag = true;
                String unDeleteRoleId = null;
                //判断角色是否绑定人员，如果绑定人员，则不能删除
                for(int i=0;i<roleIds.length;i++){
                    int num = roleService.countUserRoleByRoleId(roleIds[i]);
                    if(num>0){
                        unDeleteRoleId = roleIds[i];
                        deleteFlag = false;
                        break;
                    }
                }
                if(deleteFlag){
                    roleService.deleteRole(roleIds);
                }else{
                    rs.setSuccess(false);
                    String roleName = roleService.findRoleListByRoleName(unDeleteRoleId,null).get(0).getRoleName();
                    rs.setErrorMsg("角色"+roleName+"已分配,不能删除！");
                }
            }else{
                rs.setSuccess(false);
                rs.setErrorMsg("角色id不能为空！");
            }
            LOG.info("删除角色成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("删除角色失败！");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 查询条件：用户名称（userName）、员工编号（erpNo）
     * 传参：角色id（roleId）
     */
    @ApiOperation(value = "查询已分配用户角色列表",notes = "查询已分配用户角色列表,查询条件：用户名称（userName）、员工编号（erpNo）,传参：角色id（roleId）",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "roleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/allocatedList")
    public ResultData allocatedList(@RequestBody RoleQueryVo roleQueryVo, Page<IscUser> page, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            IscUser iscUser = new IscUser();
            iscUser.setName(roleQueryVo.getUserName());
            iscUser.setFax(roleQueryVo.getErpNo());
            String roleId = roleQueryVo.getRoleId();

            if(StringUtils.isBlank(roleId)){
                rs.setSuccess(false);
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            User user = this.getLoginUserInfo(request);
            iscUser.setBaseorgId(user.getBaseOrgId());
            roleService.selectAllocatedPageUser(page,iscUser,roleId);
            rs.setData(page);
            LOG.info("查询已分配用户角色列表成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("查询已分配用户角色列表失败！");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 查询条件：用户名称（userName）、员工编号（erpNo）
     * 传参：角色id（roleId）
     */
    @ApiOperation(value = "查询未分配用户角色列表",notes = "查询未分配用户角色列表,查询条件：用户名称（userName）、员工编号（erpNo）,传参：角色id（roleId）",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "roleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/unallocatedList")
    public ResultData unallocatedList(@RequestBody RoleQueryVo roleQueryVo, Page<IscUser> page, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            IscUser iscUser = new IscUser();
            iscUser.setName(roleQueryVo.getUserName());
            iscUser.setFax(roleQueryVo.getErpNo());
            String roleId = roleQueryVo.getRoleId();

            if(StringUtils.isBlank(roleId)){
                rs.setSuccess(false);
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            User user = this.getLoginUserInfo(request);
            iscUser.setBaseorgId(user.getBaseOrgId());
            roleService.selectUnAllocatedPageUser(page,iscUser,roleId);
            rs.setData(page);
            LOG.info("查询未分配用户角色列表成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("查询未分配用户角色列表失败！");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 传参：角色id（roleId），用户id数组（userIds）
     */
    @ApiOperation(value = "批量取消授权用户",notes = "批量取消授权用户,传参：角色id（roleId），用户id数组（userIds）",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "roleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/cancelAllRoleAndUser")
    public ResultData cancelAllRoleAndUser(@RequestBody RoleQueryVo roleQueryVo, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            String roleId = roleQueryVo.getRoleId();
            String[] userIds = roleQueryVo.getUserIds();

            rs.setSuccess(false);
            if(StringUtils.isBlank(roleId)){
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            if(null==userIds||userIds.length==0){
                rs.setErrorMsg("用户id不能为空！");
                return rs;
            }
            roleService.deleteAuthUsers(roleId,userIds);
            rs.setSuccess(true);
            LOG.info("批量取消授权用户成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("批量取消授权用户失败！");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 传参：角色id（roleId），用户id数组（userIds）
     */
    @ApiOperation(value = "批量选择用户授权",notes = "批量选择用户授权,传参：角色id（roleId），用户id数组（userIds）",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "roleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/addRoleAndUser")
    public ResultData addRoleAndUser(@RequestBody RoleQueryVo roleQueryVo, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            String roleId = roleQueryVo.getRoleId();
            String[] userIds = roleQueryVo.getUserIds();

            rs.setSuccess(false);
            if(StringUtils.isBlank(roleId)){
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            if(null==userIds||userIds.length==0){
                rs.setErrorMsg("用户id不能为空！");
                return rs;
            }
            roleService.saveUserRole(roleId,userIds);
            rs.setSuccess(true);
            LOG.info("批量选择用户授权成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("批量选择用户授权失败！");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 传参：角色id数组（roleIds），用户id（userId）
     */
    @ApiOperation(value = "用户批量取消授权",notes = "用户批量取消授权,传参：角色id数组（roleIds），用户id（userId）",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "roleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/cancelAllRoleAndUserByUserId")
    public ResultData cancelAllRoleAndUserByUserId(@RequestBody RoleQueryVo roleQueryVo, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            String userId = roleQueryVo.getUserId();
            String[] roleIds = roleQueryVo.getRoleIds();

            rs.setSuccess(false);
            if(StringUtils.isBlank(userId)){
                rs.setErrorMsg("用户id不能为空！");
                return rs;
            }
            if(null==roleIds||roleIds.length==0){
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            roleService.deleteAuthUsersByUserId(userId,roleIds);
            rs.setSuccess(true);
            LOG.info("用户批量取消授权成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("用户批量取消授权失败！");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 传参：角色id数组（roleIds），用户id（userId）
     */
    @ApiOperation(value = "用户批量选择授权",notes = "用户批量选择授权,传参：角色id数组（roleIds），用户id（userId）",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "roleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/addRoleAndUserByUserId")
    public ResultData addRoleAndUserByUserId(@RequestBody RoleQueryVo roleQueryVo, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            String userId = roleQueryVo.getUserId();
            String[] roleIds = roleQueryVo.getRoleIds();

            rs.setSuccess(false);
            if(StringUtils.isBlank(userId)){
                rs.setErrorMsg("用户id不能为空！");
                return rs;
            }
            if(null==roleIds||roleIds.length==0){
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            roleService.saveUserRoleByUserId(userId,roleIds);
            rs.setSuccess(true);
            LOG.info("用户批量选择授权成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("用户批量选择授权失败！");
            e.printStackTrace();
        }
        return rs;
    }

    @ApiOperation(value = "加载对应用户的角色列表",notes = "加载对应用户的角色列表",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "userRoleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/getRoleByUser")
    public ResultData getRoleByUser(@RequestBody UserRoleQueryVo userRoleQueryVo, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            User user = this.getLoginUserInfo(request);
            List<TSysRole> list = roleService.getRoleList(userRoleQueryVo.getRoleName(),userRoleQueryVo.getRoleCode(),userRoleQueryVo.getStatus(),user.getBaseOrgId());
            Map map = new HashMap<>();
            map.put("roles",list); //全部角色
            if(StringUtils.isBlank(userRoleQueryVo.getErpNo())){
                map.put("checkedKeys",""); //人员对应角色id
            }else{
                List<String> checkedKeys = roleService.selectRoleIdListByUserId(userRoleQueryVo.getErpNo());
                map.put("checkedKeys",checkedKeys); //人员对应角色id
            }

            rs.setData(map);
            rs.setSuccess(true);
            LOG.info("获取对应用户的角色列表成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("获取对应用户的角色列表失败！");
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 传参：角色id数组（roleIds），用户id（userId）
     */
    @ApiOperation(value = "用户批量选择角色授权",notes = "用户批量选择角色授权（先删除已关联角色，再新增关联角色）,传参：角色id数组（roleIds），用户id（userId）",httpMethod = "POST")//描述接口
    @ApiImplicitParam(name = "roleQueryVo", value = "entity", required = false, dataType = "RoleQueryVo")
    @RequestMapping("/addUserRoleByUserId")
    public ResultData addUserRoleByUserId(@RequestBody RoleQueryVo roleQueryVo, HttpServletRequest request) {
        ResultData rs = new ResultData();
        try {
            String userId = roleQueryVo.getUserId();
            String[] roleIds = roleQueryVo.getRoleIds();

            rs.setSuccess(false);
            if(StringUtils.isBlank(userId)){
                rs.setErrorMsg("用户id不能为空！");
                return rs;
            }
            if(null==roleIds||roleIds.length==0){
                rs.setErrorMsg("角色id不能为空！");
                return rs;
            }
            roleService.addUserRoleByUserId(userId,roleIds);
            rs.setSuccess(true);
            LOG.info("用户批量选择授权成功！");
        } catch (Exception e) {
            rs.setSuccess(false);
            rs.setErrorMsg("用户批量选择授权失败！");
            e.printStackTrace();
        }
        return rs;
    }


}
